﻿using IT_RoadBlock.Comands;
using IT_RoadBlock.DataContexts;
using IT_RoadBlock.Dto;
using IT_RoadBlock.Entities;
using IT_RoadBlock.Handlers;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;

namespace IT_RoadBlock.ViewModes
{
    public class ProjectInjectionEditViewModel : EditRelayCommand<TProjectInjectionInfo>
    {
        public FyDbContext DbContext = new FyDbContext();
        private List<TProjectInfo> comboxList;

        public List<TProjectInfo> ComboxList { get => comboxList; set {
                comboxList = value;
            }
        }


        public ProjectInjectionEditViewModel(TProjectInjectionInfo item)
        {
            this.CurData = item;
            IQueryable<TProjectInfo> queryables = DbContext.TProjectInfoDbSet.Where(p => 1 == 1);
            Dictionary<IGrouping<string, TProjectInfo>, TProjectInfo[]> dictionaries = queryables.GroupBy(p => p.ProjectCode).ToDictionary(p => p, p => p.ToArray());
            List<TProjectInfo> list = new List<TProjectInfo>();
            foreach (var entry in dictionaries)
            {
                list.Add(entry.Value.First());
            }
           this.ComboxList = list;
        }

        protected override void SaveItemCmdExecute(TProjectInjectionInfo obj)
        {
            StringBuilder sbf = new StringBuilder();
            TProjectInjectionInfo curData = this.CurData;
            if (string.IsNullOrWhiteSpace(curData.Fragment))
            {
                sbf.Append("代码片段不能为空");
            }
            if (string.IsNullOrWhiteSpace(curData.TruthfulMean))
            {
                sbf.Append("真实意图不能为空");
            }
            if (string.IsNullOrWhiteSpace(curData.ShamMean))
            {
                sbf.Append("lie主题曲不能为空");
            }

            if (sbf.Length > 0)
            {
                Result result = ResultFactory.Fail(sbf.ToString());
                DialogWindow?.Invoke(this, result);
            }
            else
            {
                curData.HashCode = Guid.NewGuid().ToString("N").Substring(6, 20) + (Convert.ToInt32(DateTime.Now.ToString("yyyyMMddHH"))-2008000100);
                curData.CreateTime = curData.CreateTime ?? new System.DateTime();
                DbContext.InjectionDbSet.AddOrUpdate(curData);
                DbContext.SaveChanges();
                DialogWindow?.Invoke(this, ResultFactory.Ok());
            }
        }

        ~ProjectInjectionEditViewModel()
        {
            DbContext?.Dispose();
        }
    }
}
